package middleware

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
)

// TimingMiddlewareBefore 记录请求开始时间
func TimingMiddlewareBefore() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		startTime := time.Now()
		ctx.Set("startTime", startTime) // 存入上下文
		ctx.Next()                      // 继续处理请求
	}
}

// TimingMiddlewareAfter 记录总的响应时间并设置到上下文中
func TimingMiddlewareAfter() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 从上下文中取出开始时间
		startTimeVal, exists := ctx.Get("startTime")
		if !exists {
			fmt.Println("startTime not found in context")
			return
		}

		// 计算总耗时
		startTime := startTimeVal.(time.Time)
		elapsedTime := time.Since(startTime)
		ctx.Set("elapsedTime", fmt.Sprintf("%v", elapsedTime))

		// 输出日志，检查时间
		fmt.Println("Total elapsed time:", elapsedTime)
	}
}
